package com.hexiang.rocketmq.producer.transaction;

import com.hexiang.rocketmq.producer.transaction.listener.DemoTransactionListenerImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

@Component
@Slf4j
public class DemoTransactionMQProducer {

    private final String TOPIC = "test_transaction_topic";

    private TransactionMQProducer transactionMQProducer;

    private String producerGroup = "demo_transaction_producer_group";

    private String nameServer = "127.0.0.1:9876";

    @Resource
    private DemoTransactionListenerImpl demoTransactionListener;


    @PostConstruct
    public void start() throws MQClientException {
        transactionMQProducer = new TransactionMQProducer(producerGroup,getAclRPCHook());
        transactionMQProducer.setNamesrvAddr(nameServer);
        transactionMQProducer.setTransactionListener(demoTransactionListener);
        transactionMQProducer.start();
    }

    @PreDestroy
    public void shutdown() {
        transactionMQProducer.shutdown();
    }

    RPCHook getAclRPCHook() {
        return new AclClientRPCHook(new SessionCredentials("rocketmq_u1","12345678"));
    }
    /**
     * 发送事务消息
     */
    public void sendTransactionMsg(String msgBody) {
        try {
            Message message = new Message(TOPIC, (msgBody).getBytes(RemotingHelper.DEFAULT_CHARSET));
            message.putUserProperty("myMsgId", "1232312");

            SendResult sendResult = transactionMQProducer.sendMessageInTransaction(message, null);
            log.warn("sendResult={}", sendResult);
        } catch (UnsupportedEncodingException e) {
            log.error("sendTransactionMsgErr", e);
        } catch (MQClientException e) {
            log.error("sendTransactionMsgErr", e);
        }

    }

}